package com.ztesoft.sca.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.qualitycheck.model.v20160801.GetDataSetListRequest;
import com.aliyuncs.qualitycheck.model.v20160801.GetDataSetListResponse;
import com.aliyuncs.qualitycheck.model.v20160801.GetDataSetListResponse.DataSet;
import com.ztesoft.sca.common.Constants;
import com.ztesoft.sca.common.SysConstant;
import com.ztesoft.sca.dao.DataSetDao;
import com.ztesoft.sca.model.DataSetModel;
import com.ztesoft.sca.service.DataSetService;
import com.ztesoft.sca.util.exception.ExceptionUtil;
import com.ztesoft.sca.util.message.ResponseUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/*
 * zxz 数据集
 * */

@RestController
public class DataSetController {
	private static Logger logger = Logger.getLogger(AiChatController.class);
    @Autowired
    private DataSetService dataSetService; 
	
    
	/*
	 * 获取数据集 
	 * */
	@RequestMapping(value = "/aichat/SCADataSetList",method = {RequestMethod.POST})
	public String dataSetlist(@RequestBody String requestBody,HttpServletRequest request) {
        JSONObject jsonList = JSONObject.fromObject(requestBody);
		if(jsonList == null){
			return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,Constants.INF_DESC_NULL_REQUESTBODY);
		}
        
        List< Long> setIdList=new ArrayList<Long>();
        JSONArray setIdListData = jsonList.getJSONArray("setIdList");
        for (int i = 0; i < setIdListData.size(); i++) {  
        	setIdList.add(setIdListData.getLong(i));  
        } 
        JSONArray jsonDataSet =null;
        List<DataSet> resultGet=null;
        
        try{
			IClientProfile profile = DefaultProfile.getProfile(SysConstant.REGION_ID, SysConstant.ACCESS_KEY_ID, SysConstant.ACCESS_KEY_SECRET);
			DefaultProfile.addEndpoint(SysConstant.ENDPOINT_NAME, SysConstant.REGION_ID, SysConstant.PRODUCT, SysConstant.DOMAIN);
			IAcsClient client = new DefaultAcsClient(profile);

	        GetDataSetListRequest getDataSetListRequest = new GetDataSetListRequest();
	        getDataSetListRequest.setAcceptFormat(FormatType.JSON);
	        Map<String, Object> callMap =  new HashMap<String, Object>();
	        callMap.put("appKey", SysConstant.APP_KEY );
	        if(!setIdList.isEmpty()){
	        	callMap.put("setIdList", setIdList);
	        }
	        getDataSetListRequest.setJsonStr(JSON.toJSONString(callMap));
	        GetDataSetListResponse response = client.getAcsResponse(getDataSetListRequest);
	        
	        resultGet=response.getData();
	        
	        JSONObject json = JSONObject.fromObject(response);
	         jsonDataSet = json.getJSONArray("data");
	        logger.info("----jsonDataSet----"+jsonDataSet+"--jsonDataSet.size()---"+jsonDataSet.size());
	        
	        //查询数据集ID
	        List<DataSetModel> dataSetIdStr = null;
			try {
				dataSetIdStr = this.dataSetService.selectDataSetList();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	        String dataStr="";
	        if(dataSetIdStr!=null){
		        for(DataSetModel  stu :  dataSetIdStr ){
		        	dataStr=dataStr+","+stu.getSetId();
		    	}
        	}
	        //获取阿里云的数据集批量入库
	        List<DataSetModel> listUpdate = new ArrayList<DataSetModel>();
	        List<DataSetModel> list = new ArrayList<DataSetModel>();
	        for (int i = 0; i < jsonDataSet.size(); i++) {  
	        	String setIdStr=Long.toString(resultGet.get(i).getSetId());
	        	
	        	//更新
	        	if(dataStr.indexOf(setIdStr)>-1){
		        	listUpdate.add(new DataSetModel(resultGet.get(i).getSetId(),resultGet.get(i).getSetName(),
		        			 resultGet.get(i).getSetDomain(),resultGet.get(i).getSetFolderName(),resultGet.get(i).getSetRoleArn(),
		        			 resultGet.get(i).getChannelType(),resultGet.get(i).getCreateType()));
	        	}else{
	        	//首次入库
	        	 list.add(new DataSetModel(resultGet.get(i).getSetId(),resultGet.get(i).getSetName(),
	        			 resultGet.get(i).getSetDomain(),resultGet.get(i).getSetFolderName(),resultGet.get(i).getSetRoleArn(),
	        			 resultGet.get(i).getChannelType(),resultGet.get(i).getCreateType()));
	        	} 
	        } 
	        
	      //新增数据集到本地库
	        try {
				this.dataSetService.updateDataSet(listUpdate);
				this.dataSetService.addDataSet(list);
			} catch (Exception e) {
				 logger.error(" aiChatAudioList occur an error!",e);
				 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
			}
	        //返回所有数据集到前台
			
        }catch (ServerException e) {
			 logger.error(" aiChatAudioList occur an error!",e);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
		} catch (ClientException e) {
			 logger.error(" aiChatAudioList occur an error!",e);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
		}
        
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,jsonDataSet);
	}
}
